package main

import (
	"fmt"
	"runtime"
	"sync"
	"time"
)

func add(x, y int, w *sync.WaitGroup) int {
	var c int
	w.Done() // 计数器-1
	fmt.Printf("1 return c = %d\n", c)
	defer func() { fmt.Printf("2 return c = %d\n", c) }()
	fmt.Printf("3 add called, x=%d, y=%d\n", x, y)
	c = x + y
	time.Sleep(time.Second * 5)
	return c
}

func main() {
	defer func() {
		err := recover()
		fmt.Println(err, "!!!!!!!!!!!!@@@@@@@@@@")
	}()
	var wg sync.WaitGroup // countdown 倒计数器，计数为 0则不用再wait
	wg.Add(1)
	fmt.Println(runtime.NumGoroutine())
	fmt.Println("4 main start")
	// add(4, 5) // 普通函数调用，返回才能走到下一行
	go add(4, 5, &wg) // 创建协程
	fmt.Println(runtime.NumGoroutine())
	// time.Sleep(time.Second)
	wg.Wait()
	fmt.Println("5 main end")
	fmt.Println(runtime.NumGoroutine())
}
